package util

import (
	"fmt"
	"github.com/spf13/viper"
	"path"
	"runtime"
)

var (
	ProjectRootPath = path.Dir(getCurrentPath() + "/../")
)

func getCurrentPath() string {
	_, filename, _, _ := runtime.Caller(0)
	return path.Dir(filename)
}

func CreateConfig(file string) *viper.Viper {
	cfg := viper.New()
	cfgPath := ProjectRootPath + "/config/"
	cfg.AddConfigPath(cfgPath)
	cfg.SetConfigName(file)
	cfg.SetConfigType("yaml")
	cfgFile := cfgPath + file + ".yaml"

	if err := cfg.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			panic(fmt.Errorf("找不到配置文件：%s", cfgFile))
		} else {
			panic(fmt.Errorf("解析配置文件【%s】出错，error：%v", cfgFile, err))
		}
	}
	return cfg
}
